﻿
function auto_transform(){

     //当前时间，用时间做密钥，以达到每次都是不同的密钥密码
    var time_now = new Date().getTime().toString();

    //form数量
    var form_count = document.getElementsByTagName("form").length;

    var form = [];
    var form_onsubmit = [];

    for ( i=0; i<form_count; i++ ){
        
        form[i] = document.getElementsByTagName("form")[i];
        form_onsubmit[i] = form[i].onsubmit;
     
        document.getElementsByTagName("form")[i].onsubmit = function (){
            
            //this是HTMLFormElement
            
            for( k=0; k<form_count; k++){
                
                if( form[k].name == this.name ){
                    
                    //原始submit，不能直接执行：form_onsubmit[k]，原因，执行时this会成为form_onsubmit，执行会出错
                    var pre_submit = form_onsubmit[k];
                    if(pre_submit != null){

                        pre_submit();
                        
                    }
                }
            }
            
            //不处理get请求
            var form_method = this.method;
            if ( form_method == undefined){
                return true;
            }
            if( form_method.toString().toLowerCase() == "get"){
                return true;
            }
            
            for(j=0; j< this.length; j++){
                
                var name = this.elements[j].name;
                if( name ){
                    this.elements[j].name = Secret_Key(this.elements[j].name,time_now,"encryption");
                }

                var id = this.elements[j].id;
                if( id ){
                    this.elements[j].id = Secret_Key(this.elements[j].id,time_now,"encryption");
                }

                //name或id值，首次提交时，长度不会太大，如果太大，可能是用了返回按钮
                if(( this.elements[j].name.length > 64) || ( this.elements[j].id.length >64 )){
                    alert("请刷新页面后再提交。")
                    return false;
                }
            }

            //新增一个参数，传递变形密钥
            var new_element = document.createElement("input");
            new_element.setAttribute("type","hidden");
            new_element.name = "sharewaf_transform_key";
            new_element.value = time_now;
            this.appendChild(new_element);
            
        }
    }
}

var pre_window_load=window.onload;
if (pre_window_load!=undefined){
    pre_window_load();
}
window.onload=function(){
    auto_transform();
    console.log("auto_transform module loaded");
};
